package org.EasyDevelop.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 读取配置文件
 */
public class PropertiesUtils {
    private static Properties props = new Properties();
    private static Map<String,String> PROPERTIES_MAP = new ConcurrentHashMap<>();
    static {
        InputStream is = null;
        try{
            //properties
            //流读取
            is = PropertiesUtils.class.getClassLoader().getResourceAsStream("application.properties");
            //加载到Properties中
            props.load(new InputStreamReader(is,"UTF8"));
            //迭代器迭代获取属性并且加入到Map中,方便后续获取
            Iterator<Object> iterator = props.keySet().iterator();
            while(iterator.hasNext()){
                String key = (String) iterator.next();
                PROPERTIES_MAP.put(key,props.getProperty(key));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //关闭流
            if(is!=null){
                try{
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * PROPERTIES_MAP后续获取属性的方法
     * @param key
     * @return
     */
    public static String getValue(String key){
        return PROPERTIES_MAP.get(key);
    }

    public static void main(String[] args) {
        System.out.println(PropertiesUtils.getValue("db.url"));
    }
}
